using System;
using Urs.Core;
using Urs.Data.Domain.Users;
using Urs.Core.Infrastructure;
using Urs.Data.Domain.Configuration;
using Urs.Data.Domain.Users;
using Urs.Services.Common;
using Urs.Services.Localization;
using Urs.Services.Media;
using Urs.Services.Authentication.External;
using Urs.Data.Domain.Media;
using System.Linq;

namespace Urs.Services.Users
{
    public static class UserExtentions
    {
        public static string GetFullName(this User user)
        {
            if (user == null)
                throw new ArgumentNullException("user");
            var fullName = user.Nickname ?? user.PhoneNumber ?? user.Email;

            return fullName;
        }

        public static string FormatUserName(this User user, bool stripTooLong = false, int maxLength = 0)
        {
            if (user == null)
                return string.Empty;

            if (user.IsGuest())
            {
                return EngineContext.Current.Resolve<ILocalizationService>().GetResource("User.Guest");
            }

            string result = string.Empty;
            switch (EngineContext.Current.Resolve<UserSettings>().UserNameFormat)
            {
                case UserNameFormat.ShowFullNames:
                    result = user.GetFullName();
                    break;
                default:
                    break;
            }

            if (stripTooLong && maxLength > 0)
            {
                result = CommonHelper.EnsureMaximumLength(result, maxLength);
            }

            return result;
        }


        public static string GetAvatarUrl(this User user)
        {
            if (user == null)
            {
                var dpictureService = EngineContext.Current.Resolve<IPictureService>();

                return dpictureService.GetDefaultPictureUrl(defaultPictureType: PictureType.Avatar);
            }

            var openAuthenticationService = EngineContext.Current.Resolve<IOpenAuthenticationService>();
            var ear = openAuthenticationService.GetExternalIdentifiersFor(user).FirstOrDefault();

            if (ear != null)
            {
                if (string.IsNullOrWhiteSpace(user.Nickname))
                    user.Nickname = ear.Name;
                if (!string.IsNullOrWhiteSpace(ear.AvatarUrl))
                    return ear.AvatarUrl;
            }

            var pictureService = EngineContext.Current.Resolve<IPictureService>();
            return pictureService.GetPictureUrl(user.AvatarPictureId, defaultPictureType: PictureType.Avatar);
        }

    }
}
